<?php
/**
 * 充值提现类
 * Created by PhpStorm.
 * User: 王海东
 * Date: 2018/12/17
 * Time: 14:00
 */

namespace app\common\model;
use think\Db;

class DepositWithdraw
{
    private const TAB_NAME  = 'deposit_withdraw';
    private const TAB_USER  = 'user';
    private const TAB_BANK  = 'bankinfo';

    /**
     * 新增充值提现记录
     * @author 王海东
     * @date
     * @param int   $user_id    用户id
     * @param array $data [
     *      trade_no    订单号
     *      msg         充值或提现方式
     *      fee         手续费
     *      amount    充值或提现金额
     *      type      1充值 2提现
     *      bank_id   银行卡id
     *      status    1，处理中；2，成功；3，失败; 4：审核成功（仅对提现）; 5：审核失败（仅对提现）
     * ]
     * @return bool
     * @throws \Exception
     */
    public function add(int $user_id,array $data)
    : bool {

        $insert = [
            'user_id'       => $user_id,
            'trade_no'      => $data['trade_no'],
            'msg'           => $data['msg'],
            'fee'           => $data['fee'] ?? '',
            'amount'        => $data['amount'],
            'type'          => $data['type'],
            'bank_id'       => $data['bank_id'] ?? '',
            'status'        => 1,
            'ip'            => $_SERVER['REMOTE_ADDR'],
            'create_time'   => date('Y-m-d H:i:s')
        ];

        try {
            return Db::name(self::TAB_NAME)
                    ->insertGetId($insert) ? true : false;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 充值或提现记录
     * @author 王海东
     * @date
     * @param int   $admin_id   管理员id
     * @param array $map    检索条件
     *     [
     *          start_time  开始时间
     *          end_time    截止时间
     *          name        用户名或手机号
     *          type        1 充值 2提现
     *          trade_no    订单号
     *          status      记录状态 1，处理中；2，成功；3，失败; 4：审核成功（仅对提现）; 5：审核失败（仅对提现）
     *          agent_name  管理员名称
     *     ]
     * @param int   $page       页码
     * @param int   $pageSize   页幅
     * @return array
     * @throws \Exception
     */
    public function select(int $admin_id,array $map=[],int $page,int $pageSize)
    :array {
        $db = Db::name(self::TAB_NAME);

        $db->alias('d')->join(self::TAB_USER.' u','d.user_id = u.id');

        $field = [
            'd.trade_no',
            'd.msg',
            'd.fee',
            'd.amount',
            'd.status',
            'd.ip',
            'd.create_time',
            'd.update_time',
            'u.name',
            'u.tel',
            'u.admin_id'
        ];


        if(isset($map['type'])) {

            if($map['type'] == 2) {
                $db->join(self::TAB_BANK.' b','d.bank_id = b.id','left');
                $field = [
                    'd.trade_no',
                    'd.msg',
                    'd.fee',
                    'd.amount',
                    'd.status',
                    'd.ip',
                    'd.create_time',
                    'd.update_time',
                    'u.name',
                    'u.tel',
                    'u.admin_id',
                    'b.bankname',
                    'b.bank_card_num',
                    'b.bank_branch',
                    'b.busername',
                    'b.mobile'
                ];
            }

            $db->where('d.type',$map['type']);
        }
        if (isset($map["start_time"])) {
            $db->where("d.create_time", ">= TIME", $map["start_time"]);
        }
        if (isset($map["end_time"])) {
            $db->where("d.create_time", "<= TIME", $map["end_time"]);
        }

        if(isset($map['name'])) {
            $db->where('u.name|u.tel',$map['name']);
        }

        if(isset($map['trade_no'])) {
            $db->where('d.trade_no',$map['trade_no']);
        }

        if(isset($map['status'])) {
            $db->where('d.status',$map['status']);
        }

        $a      = new Admin();
        $ids    = $a->getIds($admin_id);

        if(isset($map['agent_name'])) {

            $agent = $a->getAdminByName($map['agent_name']);
            if($agent) {
                $agent_id = $agent['id'];
                if(!in_array($agent_id,$ids)) {
                    $ids = 0;
                } else {
                    $ids = $a->getIds($agent_id);
                }
            } else {
                $ids = 0;
            }
        }

        $db->where('u.admin_id','in',$ids);


        //查询总数
        $count = $db->count("d.id");
        if ($count < 1) {
            return [
                "count" => 0,
                "list"  => [],
            ];
        }

        try {
            $list = $db->field($field)
                       ->order('d.create_time', 'desc')
                       ->page($page,$pageSize)
                       ->select();

            $a          = new Admin();
            $admin      = $a->getAdmin();

            foreach ($list as $key => $val) {
                $list[$key]['admin_name']     = $admin[$val['admin_id']]['name'];
            }

            return [
                "count" => $count,
                "list"  => $list,
            ];
        } catch (\Exception $e) {
            throw new \Exception('查询错误');
        }
    }

    /**
     * 修改充值或提现状态
     * @author 王海东
     * @date
     * @param int $id       记录id
     * @param int $status   状态 1，处理中；2，成功；3，失败; 4：审核成功（仅对提现）; 5：审核失败（仅对提现）
     * @return bool
     * @throws \Exception
     */
    public function examine(int $id,int $status)
    :bool {
        try {
            return Db::name(self::TAB_NAME)
              ->where('id',$id)
              ->update(['status' => $status,'update_time' => date('Y-m-d H:i:s')]) ? true : false;
        } catch (\Exception $e) {
            throw new \Exception('修改失败');
        }
    }

    /**
     * 查询记录详情
     * @author 王海东
     * @date
     * @param int $id   记录id
     * @return array|null|\PDOStatement|string|\think\Model
     * @throws \Exception
     */
    public function find(int $id)
    {
        try {
            return Db::name(self::TAB_NAME)
              ->field('id,user_id,trade_no,amount,status,type')
              ->where('id',$id)
              ->find() ?? [];
        } catch (\Exception $e) {
            throw new \Exception('查询失败');
        }

    }

    /**
     * 用户充值或提现记录
     * @author 王海东
     * @date
     * @param int $user_id  用户id
     * @param int $type     记录类型 1充值 2提现
     * @param int $page     页码
     * @param int $pageSize 页幅
     * @return array
     * @throws \Exception
     */
    public function userList(int $user_id,int $type,int $page,int $pageSize)
    :array {
        $db = Db::name(self::TAB_NAME);

        $db->alias('d')->join(self::TAB_USER.' u','d.user_id = u.id');

        $field = [
            'd.trade_no',
            'd.msg',
            'd.fee',
            'd.amount',
            'd.status',
            'd.ip',
            'd.create_time',
            'd.update_time',
            'u.name',
            'u.tel'
        ];

        if($type == 2) {
            $db->join(self::TAB_BANK.' b','d.bank_id = b.id','left');
            $field = [
                    'd.trade_no',
                    'd.msg',
                    'd.fee',
                    'd.amount',
                    'd.status',
                    'd.ip',
                    'd.create_time',
                    'd.update_time',
                    'u.name',
                    'u.tel',
                    'b.bankname',
                    'b.bank_card_num',
                    'b.bank_branch',
                    'b.busername',
                    'b.mobile'
                ];
        }


        if($type) {
            $db->where('d.type',$type);
        }

        $db->where('d.user_id',$user_id);

        //查询总数
        $count = $db->count("d.id");
        if ($count < 1) {
            return [
                "count" => 0,
                "list"  => [],
            ];
        }

        try {
            $list = $db->field($field)
                       ->order('d.create_time', 'desc')
                       ->page($page,$pageSize)
                       ->select();

            return [
                "count" => $count,
                "list"  => $list,
            ];
        } catch (\Exception $e) {
            throw new \Exception('查询错误');
        }
    }
}